package com.future.common.interceptor;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.future.common.annotation.LogExecutionTime;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.kit.JsonKit;

import lombok.extern.slf4j.Slf4j;
/**
 * 记录方法的执行时间，需要在方法上加入@LogExecutionTime注解
 * @author Leon.Zhang
 *
 */
@Slf4j
@SuppressWarnings("rawtypes")
public class LogExecutionTimeInterceptor implements Interceptor {

	@Override
	public void intercept(Invocation inv) {
		LogExecutionTime logExecutionTime = inv.getMethod().getAnnotation(LogExecutionTime.class);
		if(logExecutionTime !=null){
			Map<String, Object> logMap = new HashMap<String, Object>();
			Class currentClass = this.getUsefulClass(inv.getTarget());
			String className = currentClass.getName();
			String methodName = inv.getMethodName();
			Object[] args = inv.getArgs();
			Date startTime = new Date();
			logMap.put("className", className);
			logMap.put("methodName", methodName);
			logMap.put("startTime", startTime);
			
			logMap.put("args", args);
			log.info(JsonKit.toJson(logMap));
			
			inv.invoke();
			
			Date endTime = new Date();
			Long runTime = endTime.getTime() - startTime.getTime();
			logMap.remove("startTime");
			logMap.remove("requestMap");
			logMap.remove("args");
			logMap.put("endTime", new Date());
			logMap.put("runTime", runTime);
			log.info(JsonKit.toJson(logMap));
		}else{
			inv.invoke();
		}
	}
	
	private Class getUsefulClass(Object target){
		Class currentClass = target.getClass();
		currentClass  =currentClass.getName().indexOf("$$EnhancerBy") == -1 ? currentClass : currentClass.getSuperclass();
		return currentClass;
	}

}
